package com.itany.servlet;

import com.alibaba.fastjson.JSON;
import com.itany.constant.ResponseStatusConstant;
import com.itany.entity.User;
import com.itany.util.ResponseResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * Author：汤小洋
 * Date：2022-11-14 10:40
 * Description：<描述>
 */
@WebServlet("/ajax")
public class AjaxServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /**
         * 指定响应的内容类型及编码
         */
        resp.setContentType("application/json;charset=utf8");
        PrintWriter out = resp.getWriter();


        /**
         * 将Java对象转换为JSON格式字符串
         */
        User user = new User(1001, "tom", 29, "男");
        // String str = "{\"name\":"+user.getName()+",\"age\":"+user.getAge()+}";
        // String str = JSON.toJSONString(user);

        List<User> list = new ArrayList<>();
        list.add(new User(1001, "tom", 29, "男"));
        list.add(new User(1002, "jack", 29, "男"));
        list.add(new User(1003, "mike", 29, "男"));
        list.add(new User(1004, "alice", 29, "男"));
        list.add(new User(1005, "lucy", 29, "男"));

        // System.out.println(JSON.toJSONString(list));

        ResponseResult result = new ResponseResult();
        result.setStatus(ResponseStatusConstant.RESPONSE_STATUS_SUCCESS);
        result.setMessage("success");
        result.setData(list);

        out.print(JSON.toJSONString(result));
        out.close();


    }
}
